package com.yuan.util.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author YouYuan
 * @version 1.0
 * @CreateDate 2018/7/12 14:39
 * @UpdateDate 2018/7/12 14:39
 */
public class DataUtil {

    private static final ThreadLocal<ByteArrayOutputStream> LOCAL_BYTE_OUTPUT_STREAM = new ThreadLocal<ByteArrayOutputStream>(){
        @Override
        protected ByteArrayOutputStream initialValue() {
            return new ByteArrayOutputStream(1024);
        }
    };

    /**
     * 获取线程独立的可复用的ByteArrayOutputStream
     * @return
     */
    public static ByteArrayOutputStream getLocalByteOutputStream(){
        ByteArrayOutputStream outputStream = LOCAL_BYTE_OUTPUT_STREAM.get();
        outputStream.reset();
        return outputStream;
    }

    /**
     * InputStream转换成byte数组
     * @param inStream
     * @return
     * @throws IOException
     */
    public static byte[] streamToByte(InputStream inStream) throws IOException {
        int buffLength = 1024;
        byte[] buff = new byte[buffLength];
        ByteArrayOutputStream swapStream = getLocalByteOutputStream();
        int rc = 0;
        while ((rc = inStream.read(buff, 0, buffLength)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] bytes = swapStream.toByteArray();
        swapStream.reset();
        return bytes;
    }

}
